/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package edu.ncsu.utils;

import com.sun.spot.core.util.Utils;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.util.Random;

/**
 *
 * @author me
 */
public class RadioPacketSimulator {
    public static final int SIZE_IN_BYTES = 100;
    private static final int SECONDS = 1000;
    public static final int MAX_DELAY = 3*SECONDS;
    private Random rand = new Random();
    
    private ByteArrayOutputStream bos = new ByteArrayOutputStream();
    private DataOutputStream dos = new DataOutputStream(bos);

    public void writeBoolean(boolean arg0) throws IOException {
        if (bos.size() + 1 > SIZE_IN_BYTES) throw new ArrayIndexOutOfBoundsException("No more room in the packet!!");
        dos.writeBoolean(arg0);
        bos.flush();
    }

    public void writeByte(int arg0) throws IOException {
        if (bos.size() + 1 > SIZE_IN_BYTES) throw new ArrayIndexOutOfBoundsException("No more room in the packet!!");
        dos.writeByte(arg0);
        bos.flush();
    }

    public void writeChar(int arg0) throws IOException {
        if (bos.size() + 1 > SIZE_IN_BYTES) throw new ArrayIndexOutOfBoundsException("No more room in the packet!!");
        dos.writeChar(arg0);
        bos.flush();
    }

    public void writeInt(int arg0) throws IOException {
        if (bos.size() + 4 > SIZE_IN_BYTES) throw new ArrayIndexOutOfBoundsException("No more room in the packet!!");
        dos.writeInt(arg0);
        bos.flush();
    }

    public void writeLong(long arg0) throws IOException {
        if (bos.size() + 8 > SIZE_IN_BYTES) throw new ArrayIndexOutOfBoundsException("No more room in the packet!!");
        dos.writeLong(arg0);
        bos.flush();
    }

    public void writeFloat(float arg0) throws IOException {
        if (bos.size() + 4 > SIZE_IN_BYTES) throw new ArrayIndexOutOfBoundsException("No more room in the packet!!");
        dos.writeFloat(arg0);
        bos.flush();
    }

    public void writeDouble(double arg0) throws IOException {
        if (bos.size() + 8 > SIZE_IN_BYTES) throw new ArrayIndexOutOfBoundsException("No more room in the packet!!");
        dos.writeDouble(arg0);
        bos.flush();
    }

    public DataInputStream sendPacket() {
        Utils.sleep(rand.nextInt(MAX_DELAY));
        DataInputStream dis = new DataInputStream(new ByteArrayInputStream(bos.toByteArray()));
        bos.reset();
        return dis;
    }

}
